import 'package:flutter/material.dart'; // material UI包
import 'package:flutter_screenutil/flutter_screenutil.dart'; //设计图尺寸适配库
import 'dart:io'; // dart的io库 在当前页面 使用了 文件 File 存储选中的离线回复图片
import 'package:dio/dio.dart'; // http请求库
import 'package:image_picker/image_picker.dart'; // 从相册和相机选择图片

import '../widget/commit/my_appbar.dart';// my_appbar小部件

import '../model/my_store.dart'; // 全局本地存储
import '../model/config.dart';  // 全局配置文件

class OfflineReply extends StatefulWidget { // 创建OfflineReply类继承 StatefulWidget（可变状态）
  _OfflineReplyState createState() => _OfflineReplyState();
}

class _OfflineReplyState extends State<OfflineReply> with TickerProviderStateMixin{ 
  // 选中图像
  File _image;
  // 离线回复文本
  String replyText;
  // 本地的用户信息
  Map locaUser;
  // 离线回复文本输入框的控制器
  TextEditingController replyTextController;
  // 超时回复输入框控制器
  TextEditingController overtimeController;
  // 离线回复的图像地址
  String replyImage;
  // 加载提示文本
  String tipText;
  // 旋转加载动画控制器
  AnimationController controller;//动画控制器
  // 旋转加载动画运动曲线
  CurvedAnimation curved;//曲线动画，动画插值，
  // 是否开启离线回复
  bool openOvertime;
  // 超时回复事件
  int overtime;
  bool loading;
  @override
  void dispose () { // 页面销毁执行
    replyTextController.dispose();
    controller.dispose();
    super.dispose();
  }
  @override
  void initState() { // 页面创建时执行
    super.initState();
    loading = true;
    openOvertime = false;
    overtime = 0;
    tipText = '保存中...';
    replyText = '';
    // 设置显示图像初始值
    replyImage = '';
    replyTextController = TextEditingController(
      text: replyText
    );
    overtimeController = TextEditingController(
      text: overtime.toString()
    );
    replyTextController.addListener((){ // 监听文本框 变化
      setState(() {
        replyText = replyTextController.text;   
      });
    });
    // 创建动画控制器
    controller = AnimationController(
      vsync: this, duration: Duration(milliseconds: 500)
    );
    // 创建动画的运动曲线
    curved = CurvedAnimation(parent: controller, curve: Curves.linear);//匀速运动
    loadNewData();
  }

  loadNewData () async { // 获取最新的数据
    var logininfo = MyStore().getData('LOGININFO'); // 获取本地的登录信息
    var response;
    try{
      response = await Dio().get( // 从服务器请求客服的详细信息
        MyConfig().baseurl + '/csuser/getcsuser',
        data: {
          'id' : logininfo['id']
        }
      );
    } catch (e) {
      response = {
        'statusCode': 500,
        'data': {},
      };
    }
    // 先从服务器获取  获取失败在从本地获取
    var csuser;
    if (response.statusCode == 200 && response.data['status'] == 1) {
      csuser = response.data['cs_info'];
      MyStore().setData('CSUSER${logininfo['id']}', csuser);
    } else {
      csuser = MyStore().getData('CSUSER${logininfo['id']}');
    }
    var cstimeout;
    try{
      cstimeout = await Dio().post( // 从服务器请求客服的详细信息
        MyConfig().baseurl + '/gettimeout',
        data: {
          'cs_id' : logininfo['id']
        }
      );
    } catch (e) {
      cstimeout = {
        'statusCode': 500,
        'data': {},
      };
    }
    Map _cstimeout;
    if (cstimeout.statusCode == 200 && cstimeout.data['status'] == 1) {
      _cstimeout = {
        'isinure': cstimeout.data['arr']['isinure'],
        'timeout': cstimeout.data['arr']['timeout'] / 1000
      };
      print(_cstimeout);
    } else {
      _cstimeout = {
        'isinure': false,
        'timeout': 0
      };
    }

    setState(() {
      locaUser = csuser; // 设置用户信息
      replyText = locaUser['auto_reply_text']; // 初始文本
      replyImage = locaUser['auto_reply_img']; // 初始图片
      openOvertime = _cstimeout['isinure'];
      overtime = _cstimeout['timeout'].toInt();
      loading = false;
      overtimeController.text = overtime.toString();
      replyTextController.text = locaUser['auto_reply_text'];
    });
  }

  /// 渲染离线回复图像 没有的时候显示默认的
  ImageProvider renderReplyImg (String path) {
    if (_image != null) {
      return FileImage(_image);
    }
    if (path == '' || path == null) {
      return AssetImage(
        'static/defaultimg.jpg'
      );
    } else {
      return NetworkImage(MyConfig().serverurl + path);
    }
  }

    // 从本地相册或拍照获取图像
  Future getImage(ImageSource source) async {
    var image = await ImagePicker.pickImage(
      source: source
    );
    setState(() {
      _image = image;
    });
  }

  // 显示底部弹出通知条
  void showSnackBar (BuildContext context, String title, {int duration = 500, Color color = Colors.black}) {
    var snackBar = SnackBar(
      content:  Text(title),
      duration: Duration(milliseconds: duration),
      backgroundColor: color,
    );
    Scaffold.of(context).showSnackBar(snackBar);
  }

  // 保存离线回复
  saveOfflineReply (BuildContext context) async {
    setState(() {tipText = '保存中...';});
    if (_image != null) { // 判断是否有相中
      setState(() {tipText = '上传图片...';});
      FormData formData = FormData.from({
        "image": UploadFileInfo(_image, 'aaa.jpg'),
      });
      var response = await Dio().post(
        MyConfig().baseurl + '/csuser/uploadpic',
        data: formData
      );
      if (response.statusCode == 200 && response.data['error'] == 0) {
        setState(() {
          _image = null;
          replyImage = response.data['url'];
        });
      } else {
        Navigator.pop(context);
        print(response);
        showSnackBar(context, '图片上传失败,请重试！', duration: 1000);
        return;
      }
    }
    setState(() {tipText = '保存中...';});
    var saveRes = await Dio().post(
      MyConfig().baseurl + '/csuser/savereply',
      data: {
        'auto_reply_img': replyImage,
        'auto_reply_text': replyText,
        'id' : locaUser['id']
      }
    );
    Navigator.pop(context);
    print(saveRes);
    if (saveRes.statusCode == 200 && saveRes.data['status'] == 1) {
      setState(() {
        locaUser['auto_reply_text'] = replyText;
        locaUser['auto_reply_img'] = replyImage;   
      });
      MyStore().setData('CSUSER${locaUser['id']}', locaUser);
    } else {
      showSnackBar(context, '保存离线回复失败,请重试！', duration: 1000);
    }
  }

  // 保存超时回复设置
  saveOverTime (BuildContext context) async {
    print(!openOvertime);
    var data = {
      'cs_id': locaUser['id'],
      'isinure': !openOvertime,
      'timeout': overtime * 1000
    };
    var res;
    try {
      res = await Dio().post(MyConfig().baseurl + '/settimeout', data: data);
      if (res.statusCode == 200 && res.data['status'] == 1) {
        print(res);
        setState(() {
          openOvertime = !openOvertime;
          overtime = overtime;
        });
        // showSnackBar(context, '设置成功', color: Colors.redAccent);
      } else {
        // showSnackBar(context, '设置成功');
      }
    } catch (e) {
      // showSnackBar(context, '设置超时回复失败', color: Colors.redAccent);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PreferredSize(
        child: Builder(
          builder: (context) {
            return MyAppBar(
              brightness: true,
              title: '离线回复',
              actions: buttonInfo(
                icon: 0xe60c,
                onTap: (){
                  FocusScope.of(context).requestFocus(FocusNode()); // 收起键盘
                  if (replyText == locaUser['auto_reply_text'] && _image == null) {
                    print(context);
                    showSnackBar(context, '请修改内容后在提交！');
                    return;
                  }
                  controller.repeat(); // 开始加载动画
                  //显示弹窗
                  showDialog(
                    context: context,
                    barrierDismissible:false,
                    builder: (BuildContext context) {
                      return WillPopScope(
                        onWillPop: (){},
                        child: Center(
                          child: Container(
                            width: ScreenUtil().setWidth(200),
                            height: ScreenUtil().setWidth(200),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(3)
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                RotationTransition(
                                  turns: curved,
                                  child: Icon(
                                    IconData(0xe602 , fontFamily: 'iconfont'),
                                    size: ScreenUtil().setWidth(80),
                                    color: Colors.black54,
                                  )
                                ),
                                SizedBox(
                                  height:  ScreenUtil().setWidth(10)
                                ),
                                Text(
                                  tipText,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setWidth(20),
                                    color: Colors.black54
                                  ),
                                )
                              ],
                            )
                          )
                        ),
                      );
                    }
                  );
                  saveOfflineReply(context);
                }
              ),
            );
          }
        ),
        preferredSize: Size.fromHeight(ScreenUtil().setWidth(80)),
      ),
      body: loading ? Center(
        child: Text('加载中'),
      ):ListView(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(
              left: ScreenUtil().setWidth(10),
              right: ScreenUtil().setWidth(10),
              top: ScreenUtil().setWidth(20)
            ),
            child: Text('离线文本回复：'),
          ),
          Container(
            margin: EdgeInsets.all(ScreenUtil().setWidth(10)),
            padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
            height: ScreenUtil().setWidth(300),
            decoration:BoxDecoration(
              borderRadius: BorderRadius.circular(5),
              border: Border.all(
                color: Colors.black54
              )
            ),
            child: TextField(
              controller: replyTextController,
              maxLines: 1000,
              decoration: InputDecoration(
                hintText: '输入离线回复的文本消息',
                contentPadding: EdgeInsets.all(0),
                border: InputBorder.none,
                fillColor: Colors.white
              )
            )
          ),
          Padding(
            padding: EdgeInsets.only(
              left: ScreenUtil().setWidth(10),
              right: ScreenUtil().setWidth(10),
              top: ScreenUtil().setWidth(20)
            ),
            child: Text('离线文本图片：'),
          ),
          Container(
            padding: EdgeInsets.only(
              right: ScreenUtil().setWidth(470)
            ),
            child: Container(
              margin: EdgeInsets.all(ScreenUtil().setWidth(15)),
              height: ScreenUtil().setWidth(250),
              decoration: BoxDecoration(
                border: Border.all(
                  color: Colors.black38
                ),
                borderRadius: BorderRadius.circular(5),
                image: DecorationImage(
                  image: renderReplyImg(replyImage),
                  fit: BoxFit.cover
                )
              ),
              child: InkWell(
                onTap: () {
                  showModalBottomSheet(
                    context: context,
                    builder: (BuildContext context){
                      return Column( // 弹出选择打开图片方式
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          ListTile(
                            leading: Icon(
                              Icons.camera_alt
                            ),
                            title: new Text("拍照"),
                            onTap: () async {
                              Navigator.pop(context);
                              getImage(ImageSource.camera);
                            },
                          ),
                          ListTile(
                            leading: Icon(Icons.image),
                            title: new Text("相册"),
                            onTap: () async {
                              Navigator.pop(context);
                              getImage(ImageSource.gallery);
                            },
                          )
                        ],
                      );
                    }
                  );
                },
              )
            )
          ),
          // ScreenUtil().setWidth(15)
          Card(
            child: Column(
              children: <Widget>[
                InkWell(
                  child: Container(
                    width: ScreenUtil().setWidth(750),
                    height: ScreenUtil().setWidth(80),
                    padding: EdgeInsets.all(ScreenUtil().setWidth(15)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text('是否开启超时回复'),
                        Container(
                          height: ScreenUtil().setWidth(50),
                          width: ScreenUtil().setWidth(50),
                          child: Icon(
                            IconData(0xe62c , fontFamily: 'iconfont'),
                            color: openOvertime ? Colors.green : Colors.grey,
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: (){
                    saveOverTime(context);
                  },
                ),
                Container(
                  width: ScreenUtil().setWidth(750),
                  height: ScreenUtil().setWidth(1),
                  color: Colors.grey[200],
                ),
                Container(
                  width: ScreenUtil().setWidth(750),
                  height: ScreenUtil().setWidth(80),
                  padding: EdgeInsets.all(ScreenUtil().setWidth(15)),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: TextField(
                          controller: overtimeController,
                          keyboardType: TextInputType.numberWithOptions(),
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(ScreenUtil().setWidth(0))
                          ),
                          onSubmitted: (value) {
                            int size =num.parse(value);
                            print(size);
                            setState(() {
                              overtime = size;
                            });
                            saveOverTime(context);
                          },
                        ),
                      ),
                      Text('   超时事件(秒/s)'),
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      )
    );
  }
}